package com.yongchun.config.suningpay;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author 张磊
 * Date:2019-08-05
 * Time:15:57
 * 类描述:当商户使用 apache  HttpClient作为http工具类时，可参考此demo
 */
public class ApacheHttpClient {

    private ApacheHttpClient() {
    }


    public static String post(String url, String json) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault ();
        //设置请求超时时间
        RequestConfig requestConfig = RequestConfig.custom ()
                .setSocketTimeout (5000)
                .setConnectTimeout (5000)
                .setConnectionRequestTimeout (5000)
                .build ();
        try {
            HttpPost post = new HttpPost (url);
            post.setConfig (requestConfig);
            //设置发送的数据 ，注意要使用 StringEntity ,并且 字符编码一定要设置 utf-8
            StringEntity s = new StringEntity (json,"utf-8");
            //发送json数据需要设置contentType
            s.setContentType ("application/json");
            post.setEntity (s);
            //获取返回值
            CloseableHttpResponse res = closeableHttpClient.execute (post);
            if (res.getStatusLine ().getStatusCode () == HttpStatus.SC_OK) {
                // 返回json格式：
                return EntityUtils.toString (res.getEntity ());
            }
        } catch (Exception e) {
            throw new FtpgsUtils.FtpgsException ("网络请求发生了异常", e);
        } finally {
            try {                //关闭流并释放资源
                closeableHttpClient.close ();
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }
        return null;
    }
}
